/**
 * 剑指 Offer 32 - II. 从上到下打印二叉树 II
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/
 */
const { displayNestedArray, createTreeNode } = require('../../libs/public');

/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
function levelOrder(root) {
  if (!root) {
    return [];
  }
  let stack = [root];
  let stackVals = [root.val];
  const result = [];
  while (stack.length) {
    result.push(stackVals);
    const temp = [];
    stackVals = [];
    while (stack.length) {
      const node = stack.shift();
      if (node.left) {
        temp.push(node.left);
        stackVals.push(node.left.val);
      }
      if (node.right) {
        temp.push(node.right);
        stackVals.push(node.right.val);
      }
    }
    stack = temp;
  }
  return result;
}

console.log(displayNestedArray(levelOrder(createTreeNode([3, 9, 20, null, null, 15, 7]))) === '[[3],[9,20],[15,7]]');
console.log(displayNestedArray(levelOrder(createTreeNode([]))) === '[]');
